package top.zackyoung.bbs.service;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.zackyoung.bbs.bean.CreateImage;
import top.zackyoung.bbs.bean.ErrorView;
import top.zackyoung.bbs.controller.FileController;
import top.zackyoung.bbs.utils.FileUtil;
import top.zackyoung.bbs.utils.PicUtil;
import top.zackyoung.bbs.utils.RenameUtil;
import top.zackyoung.bbs.utils.Verification;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: ZackYoung
 * @time: 2020/11/13
 */
@Service
public class HdfsService {
    public static Boolean enable;

    @Value("${hdfs.enable:false}")
    public void setEnable(Boolean enable) {
        HdfsService.enable = enable;
    }

    @Value("${hdfs.path}")
    private String path;
    @Value("${hdfs.username}")
    private String username;

    private static String user;

    @Value("${hdfs.user}")
    public void setUser(String user) {
        HdfsService.user = user;
    }

    private static String imgPath;

    @Value("${img.path}")
    public void setImgPath(String imgPath) {
        HdfsService.imgPath = imgPath;
    }

    private static String hdfsPath;
    private static String hdfsName;
    private static final int bufferSize = 1024 * 1024 * 64;

    /**
     * 获取HDFS配置信息
     *
     * @return
     */
    private static Configuration getConfiguration() {
        Configuration configuration = new Configuration();
        configuration.set("fs.defaultFS", hdfsPath);
        return configuration;
    }

    /**
     * 获取HDFS文件系统对象
     *
     * @return
     * @throws Exception
     */
    public static FileSystem getFileSystem() throws Exception {
        // 客户端去操作hdfs时是有一个用户身份的，默认情况下hdfs客户端api会从jvm中获取一个参数作为自己的用户身份
        // DHADOOP_USER_NAME=hadoop
        // 也可以在构造客户端fs对象时，通过参数传递进去
        FileSystem fileSystem = FileSystem.get(new URI(hdfsPath), getConfiguration(), hdfsName);
        return fileSystem;
    }

    /**
     * 在HDFS创建文件夹
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static boolean mkdir(String path) throws Exception {
        if (StringUtils.isEmpty(path)) {
            return false;
        }
        if (existFile(path)) {
            return true;
        }
        FileSystem fs = getFileSystem();
        // 目标路径
        Path srcPath = new Path(path);
        boolean isOk = fs.mkdirs(srcPath);
        fs.close();
        return isOk;
    }

    /**
     * 判断HDFS文件是否存在
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static boolean existFile(String path) throws Exception {
        if (StringUtils.isEmpty(path)) {
            return false;
        }
        FileSystem fs = getFileSystem();
        Path srcPath = new Path(path);
        boolean isExists = fs.exists(srcPath);
        return isExists;
    }

    /**
     * 读取HDFS目录信息
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static List<Map<String, Object>> readPathInfo(String path) throws Exception {
        if (StringUtils.isEmpty(path)) {
            return null;
        }
        if (!existFile(path)) {
            return null;
        }
        FileSystem fs = getFileSystem();
        // 目标路径
        Path newPath = new Path(path);
        FileStatus[] statusList = fs.listStatus(newPath);
        List<Map<String, Object>> list = new ArrayList<>();
        if (null != statusList && statusList.length > 0) {
            for (FileStatus fileStatus : statusList) {
                Map<String, Object> map = new HashMap<>();
                map.put("filePath", fileStatus.getPath());
                map.put("fileStatus", fileStatus.toString());
                list.add(map);
            }
            return list;
        } else {
            return null;
        }
    }

    /**
     * HDFS创建文件
     *
     * @param path
     * @param file
     * @throws Exception
     */
    public static void createFile(String path, MultipartFile file) throws Exception {
        if (StringUtils.isEmpty(path) || null == file.getBytes()) {
            return;
        }
        String fileName = file.getOriginalFilename();
        FileSystem fs = getFileSystem();
        // 上传时默认当前目录，后面自动拼接文件的目录
        Path newPath = new Path(path + "/" + fileName);
        // 打开一个输出流
        FSDataOutputStream outputStream = fs.create(newPath);
        outputStream.write(file.getBytes());
        outputStream.close();
        fs.close();
    }

    /**
     * 读取HDFS文件内容
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static String readFile(String path) throws Exception {
        if (StringUtils.isEmpty(path)) {
            return null;
        }
        if (!existFile(path)) {
            return null;
        }
        FileSystem fs = getFileSystem();
        // 目标路径
        Path srcPath = new Path(path);
        FSDataInputStream inputStream = null;
        try {
            inputStream = fs.open(srcPath);
            // 防止中文乱码
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String lineTxt = "";
            StringBuffer sb = new StringBuffer();
            while ((lineTxt = reader.readLine()) != null) {
                sb.append(lineTxt);
            }
            return sb.toString();
        } finally {
            inputStream.close();
            fs.close();
        }
    }

    /**
     * 读取图片头像
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static BufferedImage readAvatar(String path) throws Exception {
        if (StringUtils.isEmpty(path)) {
            return null;
        }
        if (enable) {
            if (!existFile(path)) {
                return null;
            }
            FileSystem fs = getFileSystem();
            // 目标路径
            Path srcPath = new Path(path);
            FSDataInputStream inputStream = null;
            try {
                inputStream = fs.open(srcPath);
                BufferedImage read = ImageIO.read(inputStream);
                return read;
            } finally {
                inputStream.close();
                fs.close();
            }
        }
        // 使用本地
        return ImageIO.read(new File(imgPath + path));


    }

    public static void noImg(OutputStream os) throws IOException {
        URL resource = HdfsService.class.getClassLoader().getResource("static/images/nophoto.jpg");
        BufferedImage noImg = ImageIO.read(new File(resource.getFile()));
        ImageIO.write(noImg, "jpg", os);
    }

    public static Boolean readImg(String path, HttpServletResponse response) throws Exception {
        if (StringUtils.isEmpty(path)) {
            return false;
        }
        if (!existFile(path)) {
            return false;
        }
        FileSystem fs = getFileSystem();
        // 目标路径
        Path srcPath = new Path(path);
        FSDataInputStream inputStream = null;
        OutputStream os = null;
        try {
            inputStream = fs.open(srcPath);
            os = response.getOutputStream();
            // 图片文件流缓存池
            byte[] buffer = new byte[1024];
            while (inputStream.read(buffer) != -1) {
                os.write(buffer);
            }
            os.flush();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            os.close();
        }
        return true;
    }

    /**
     * 读取HDFS文件列表
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static List<Map<String, String>> listFile(String path) throws Exception {
        if (StringUtils.isEmpty(path)) {
            return null;
        }
        if (!existFile(path)) {
            return null;
        }

        FileSystem fs = getFileSystem();
        // 目标路径
        Path srcPath = new Path(path);
        // 递归找到所有文件
        RemoteIterator<LocatedFileStatus> filesList = fs.listFiles(srcPath, true);
        List<Map<String, String>> returnList = new ArrayList<>();
        while (filesList.hasNext()) {
            LocatedFileStatus next = filesList.next();
            String fileName = next.getPath().getName();
            Path filePath = next.getPath();
            Map<String, String> map = new HashMap<>();
            map.put("fileName", fileName);
            map.put("filePath", filePath.toString());
            returnList.add(map);
        }
        fs.close();
        return returnList;
    }

    /**
     * HDFS重命名文件
     *
     * @param oldName
     * @param newName
     * @return
     * @throws Exception
     */
    public static boolean renameFile(String oldName, String newName) throws Exception {
        if (StringUtils.isEmpty(oldName) || StringUtils.isEmpty(newName)) {
            return false;
        }
        FileSystem fs = getFileSystem();
        // 原文件目标路径
        Path oldPath = new Path(oldName);
        // 重命名目标路径
        Path newPath = new Path(newName);
        boolean isOk = fs.rename(oldPath, newPath);
        fs.close();
        return isOk;
    }

    /**
     * 删除HDFS文件
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static boolean deleteFile(String path) throws Exception {
        if (StringUtils.isEmpty(path)) {
            return false;
        }
        if (!existFile(path)) {
            return false;
        }
        FileSystem fs = getFileSystem();
        Path srcPath = new Path(path);
        boolean isOk = fs.deleteOnExit(srcPath);
        fs.close();
        return isOk;
    }

    /**
     * 上传HDFS文件
     *
     * @param path
     * @param uploadPath
     * @throws Exception
     */
    public static void uploadFile(String path, String uploadPath) throws Exception {
        if (StringUtils.isEmpty(path) || StringUtils.isEmpty(uploadPath)) {
            return;
        }
        FileSystem fs = getFileSystem();
        // 上传路径
        Path clientPath = new Path(path);
        // 目标路径
        Path serverPath = new Path(uploadPath);

        // 调用文件系统的文件复制方法，第一个参数是否删除原文件true为删除，默认为false
        fs.copyFromLocalFile(false, clientPath, serverPath);
        fs.close();
    }

    public static String uploadImage(MultipartFile file, String name) throws Exception {
        String fileName = RenameUtil.toDate();
        FileSystem fs = getFileSystem();
        String localImgPath = imgPath + fileName + ".jpg";
        File file1 = new File(localImgPath);
        file.transferTo(file1);
        // 图片按原比列压缩
        File desc = PicUtil.commpressPicForScaleSize(file1, localImgPath, 150, 0.25);
        if (enable) {
            FileInputStream in = new FileInputStream(desc);
            String hdfsPath = user + name + "/" + fileName + ".jpg";
            FSDataOutputStream out = fs.create(new Path(hdfsPath));
            IOUtils.copyBytes(in, out, getConfiguration(), true);
            desc.delete();
            return hdfsPath;
        }
        return desc.getName();
    }

    public static String uploadAvatar(MultipartFile file, String name, String _width, String _height, String _x, String _y, Map error) throws Exception {
        Integer width = null;//宽
        Integer height = null;//高
        Integer x = 0;//坐标X轴
        Integer y = 0;//坐标Y轴
        CreateImage fileManage = new CreateImage();

        if (_width != null && !"".equals(_width.trim())) {
            if (Verification.isPositiveInteger(_width.trim())) {
                if (_width.trim().length() >= 8) {
                    //不能超过8位数字
                    error.put("width", ErrorView._1200.name());
                } else {
                    width = Integer.parseInt(_width.trim());
                }
            } else {
                //宽度必须大于0
                error.put("width", ErrorView._1210.name());
            }
        }
        if (_height != null && !"".equals(_height.trim())) {
            if (Verification.isPositiveInteger(_height.trim())) {
                if (_height.trim().length() >= 8) {
                    //不能超过8位数字
                    error.put("height", ErrorView._1200.name());
                } else {
                    height = Integer.parseInt(_height.trim());
                }
            } else {
                //高度必须大于0
                error.put("height", ErrorView._1230.name());
            }
        }
        if (_x != null && !"".equals(_x.trim())) {
            if (Verification.isPositiveIntegerZero(_x.trim())) {
                if (_x.trim().length() >= 8) {
                    //不能超过8位数字
                    error.put("x", ErrorView._1200.name());
                } else {
                    x = Integer.parseInt(_x.trim());
                }
            } else {
                //X轴必须大于或等于0
                error.put("x", ErrorView._1250.name());
            }
        }
        if (_y != null && !"".equals(_y.trim())) {
            if (Verification.isPositiveIntegerZero(_y.trim())) {
                if (_y.trim().length() >= 8) {
                    //不能超过8位数字
                    error.put("y", ErrorView._1200.name());
                } else {
                    y = Integer.parseInt(_y.trim());
                }
            } else {
                //Y轴必须大于或等于0
                error.put("y", ErrorView._1270.name());
            }
        }

        // 修改文件名
        String newName = "avatar_" + FileUtil.renameImg() + ".jpg";
        String filePath = imgPath + newName;
        //生成200*200缩略图
        fileManage.createImage(file.getInputStream(), filePath, "jpg", x, y, width, height, 200, 200);
        if (enable) {
            try {
                FileSystem fs = getFileSystem();
                File file1 = new File(filePath);
                FileInputStream in = new FileInputStream(file1);
                String hdfsPath = user + name + "/" + newName;
                FSDataOutputStream out = fs.create(new Path(hdfsPath));
                IOUtils.copyBytes(in, out, getConfiguration(), true);
                file1.delete();
                error.put("success", "true");
                return hdfsPath;
            } catch (Exception e) {
                e.printStackTrace();
                error.put("success", "false");
            }
        }

        return user + name + "/" + newName;
    }


    /**
     * 下载HDFS文件
     *
     * @param path
     * @param downloadPath
     * @throws Exception
     */
    public static void downloadFile(String path, String downloadPath) throws Exception {
        if (StringUtils.isEmpty(path) || StringUtils.isEmpty(downloadPath)) {
            return;
        }
        FileSystem fs = getFileSystem();
        // 上传路径
        Path clientPath = new Path(path);
        // 目标路径
        Path serverPath = new Path(downloadPath);

        // 调用文件系统的文件复制方法，第一个参数是否删除原文件true为删除，默认为false
        fs.copyToLocalFile(false, clientPath, serverPath);
        fs.close();
    }

    /**
     * HDFS文件复制
     *
     * @param sourcePath
     * @param targetPath
     * @throws Exception
     */
    public static void copyFile(String sourcePath, String targetPath) throws Exception {
        if (StringUtils.isEmpty(sourcePath) || StringUtils.isEmpty(targetPath)) {
            return;
        }
        FileSystem fs = getFileSystem();
        // 原始文件路径
        Path oldPath = new Path(sourcePath);
        // 目标路径
        Path newPath = new Path(targetPath);

        FSDataInputStream inputStream = null;
        FSDataOutputStream outputStream = null;
        try {
            inputStream = fs.open(oldPath);
            outputStream = fs.create(newPath);

            IOUtils.copyBytes(inputStream, outputStream, bufferSize, false);
        } finally {
            inputStream.close();
            outputStream.close();
            fs.close();
        }
    }

    /**
     * 获取某个文件在HDFS的集群位置
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static BlockLocation[] getFileBlockLocations(String path) throws Exception {
        if (StringUtils.isEmpty(path)) {
            return null;
        }
        if (!existFile(path)) {
            return null;
        }
        FileSystem fs = getFileSystem();
        // 目标路径
        Path srcPath = new Path(path);
        FileStatus fileStatus = fs.getFileStatus(srcPath);
        return fs.getFileBlockLocations(fileStatus, 0, fileStatus.getLen());
    }

    @PostConstruct
    public void getPath() {
        hdfsPath = this.path;
    }

    @PostConstruct
    public void getName() {
        hdfsName = this.username;
    }

    public static String getHdfsPath() {
        return hdfsPath;
    }

    public String getUsername() {
        return username;
    }
}
